﻿
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class WhoReferencedWindow:EditorWindow
{
    static WhoReferencedWindow instance;
    Vector2 pos;
    GameObject findGameObject;
    List<Object> objects = new List<Object>();
    public GameObject gameObject
    {
        get { return findGameObject; }
        set
        {
            findGameObject = value;
            objects.Clear();
            objects.Add(value);
            objects.AddRange(value.GetComponents<Component>());
        }
    }
    public Component[] array;

    private void OnEnable()
    {
        instance = this;
    }
    private void OnDisable()
    {
        instance = null;
    }

    public static bool IsEnable()
    {
        return instance != null;
    }

    public static bool Contains(Component component)
    {
        if (instance == null)
            return false;
        return instance.array.Contains(component);
    }

    public static bool Contains(SerializedProperty serializedProperty)
    {
        if (instance == null|| serializedProperty==null)
            return false;
        if(serializedProperty.propertyType == SerializedPropertyType.ObjectReference&&serializedProperty.objectReferenceValue!=null)
        {
            return instance.objects.Contains(serializedProperty.objectReferenceValue);
        }
        return false;
    }

    private void OnGUI()
    {
        if (gameObject == null || array == null)
            return;

        pos = EditorGUILayout.BeginScrollView(pos);
        {
            GUI.enabled = false;
            EditorGUILayout.ObjectField("查询对象", gameObject, typeof(GameObject), false);
            GUI.enabled = true;
            EditorGUILayout.Space();
            var x = GUI.skin.button.alignment;
            GUI.skin.button.alignment = TextAnchor.UpperLeft;
            for(int i=0;i<array.Length;i++)
            {
                var item = array[i];
                if (GUILayout.Button(string.Format("[Gameobject] {0}\n[     Script      ] {1}", item.name, item.GetType().Name)))
                {
                    Selection.activeObject = item.gameObject;
                }
            }
            GUI.skin.button.alignment = x;
        }
        EditorGUILayout.EndScrollView();
    }
}